<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <h1>取消请求三</h1>
    <input type="text" name="" id="ipt">
    <button id="btn">点击提交</button>
    <button id="cancel">点击取消</button>


    <script>
        //获取元素
        const oBtn = document.getElementById('btn')
        const oCancel = document.getElementById('cancel');
        const oIpt = document.getElementById('ipt')

        //创建axios实例
        const myAxios = axios.create({
            baseURL : 'http://127.0.0.1:4000',
            timeout : 10000,
            headers :{
                token : 'fhiuye.fhfhd.fksdhsp'
            }
        })

        //添加取消请求的方法
        const CancelToken = axios.CancelToken;
        let  cancel = null;

        //添加请求拦截器
        axios.interceptors.request.use((config)=>{
            return config
        },(err)=>{
            throw Promise.reject(err)
        })

        //添加响应拦截器
        axios.interceptors.response.use((config)=>{
            return config.data.data
        },(err)=>{
            throw Promise.reject(err)
        })

        oBtn.onclick = async function(){
            
       console.log(111);
         
            try{
                 //获取输入的值
                const iptValue = oIpt.value
                const re = await myAxios.get('http://127.0.0.1:4000/myAxios',{
                    params:{
                        userId:iptValue
                    },
                    //当请求发送的时候，这个回调函数会被执行，并接受一个参数，这个参数就是取消请求的函数
                    cancelToken : new CancelToken((c)=>{
                    cancel = c
                    console.log(c);
                    })
                    
                })
                console.log(re.data);
            }catch(e){
                console.log(e.message);
            }
        }

        //绑定点击取消请求
        oCancel.onclick = function(){
            cancel()
        }
    </script>
</body>
</html>